import React, { Component } from 'react';
import { Slider, Progress } from 'element-react';

import './musicPlay.css'
import headerImg from '../../static/login_bg.jpg';
let pBg = {
  backgroundImage: `url(${headerImg})`,
  backgroundRepeat: 'no-repeat',
  backgroundSize: 'cover',
}
class MusicPlay extends Component {
  state = {
    id: null,
    playArr: [],
    lyricArr: [],
    timeArr: [],
    sites:0,
    volumn: 20,
    playProgess: 0,
    duration: 0,//音乐总时长
  };
  //初始化请求
  componentWillMount() {
    let id = this.props.match.params.id;
    this.setState({ id: id, playArr: [] })
  }
  // 组件加载完毕
  componentDidMount() {
    this.getSongDetailData();
  }
  componentWillUnmount() {
    console.log('详情页销毁了')
    // 卸载异步操作设置状态
    this.setState = (state, callback) => {
      return;
    }
  }
  render() {
    const { playArr, lyricArr, volumn, playProgess,sites } = this.state;
    return (
      <div className="container muiscplay">
        <div className="music-hearder">
          <img src={headerImg} alt="" />
          <div className="roate-box">
            <p style={pBg}></p>
          </div>
          {/* 歌词 */}
          <div className="lyricbox">
          <ul style={{top:`${sites}`}}>
            {
              lyricArr.map((item, index) => {
                return <li className={item.active} key={index}>{item.lyric}</li>
                
              })
            }
            </ul>
          </div>
          {/* 进度条 */}
          <Progress className="progess" percentage={playProgess} />
        </div>
        <audio src={playArr.url} controls="controls" id="audios">
          Your browser does not support the audio element.
          </audio>

        {/* 控制按钮 */}
        <div className="controls">
          <div className="down-load" onClick={()=>this.down(`${playArr.url}`)}>
            <span className="el-icon-upload2">下载</span>
          </div>
          <div className="start" onClick={this.play.bind(this)}>播放</div>
          <div className="block volume">
            <span className="demonstration">音量</span>
            <Slider value={volumn} onChange={this.setVolume.bind(this)} />
          </div>

        </div>
        
      </div>
    );
  }

  // 获取音乐信息
  getSongDetailData = () => {
    let that = this;
    let { id, volumn } = this.state;
    that.$post(that.$api.songUrl, { id: id }).then(res => {
      if (res.code === 200) {
        that.setVolume(volumn)
        that.setState({
          playArr: res.data[0],
        }, r => {
          console.log(that.state.playArr)
        });
        that.getSongLyriclData();

      }
    });
  }
  // 获取歌词
  getSongLyriclData = () => {
    let that = this;
    let { id } = that.state;
    let timeArr = [];//歌词时间
    let contentArr = [];//歌词
    that.$post(that.$api.lyric, { id: id }).then(res => {
      if (res.code === 200) {
        // console.log(res);
        let lyric = res.lrc.lyric;
        let str = lyric.split('\n');
        for (let i = 0; i < str.length; i++) {
          let obj = str[i];
          let cont = {active:'',lyric:obj.substring(obj.indexOf("]") + 1, obj.length)};
          let time = obj.substring(obj.indexOf("[") + 1, obj.indexOf("]"));
          contentArr.push(cont);
          timeArr.push(time);
        }
        this.setState({
          lyricArr: contentArr,
          timeArr: timeArr
        }, r => {
          // console.log(that.state.lyricArr)
        });

      }
    });
  }
  // 播放/停止
  play(e) {
    let { duration, timeArr, lyricArr,sites} = this.state;
    let timer1;
    var arr = [];
    let audios = document.getElementById('audios');
    this.setState({
      duration: parseInt(audios.duration)
    }, r => {
      console.log(this.state.duration)
    })

    if (audios.paused) {
      audios.play();
      
      e.target.innerHTML = '播放';
      var that = this;
      var num=0;
      // 音乐、视频播放改变事件
      audios.ontimeupdate = function(){
        let str = that.secTotime(this.currentTime);
        let nowTime = str.substring(3, str.length);
        
        for(let i=0;i<timeArr.length;i++){
          
          let obj = timeArr[i];
          if(obj < nowTime){
            // num = (i-1)*20;
            console.log(i)
            lyricArr[i].active = 'active';
            that.setState({
              lyricArr: lyricArr,
              sites: i,
            },r=>{
              console.log(that.state.sites)
            })
          }
        }
      }
      // this.playPro();
    } else {
      timer1 = null;
      audios.pause();
      e.target.innerHTML = '暂停'
    }
  }
  // 设置音量
  setVolume(value) {
    let audios = document.getElementById('audios');
    audios.volume = value / 100;
  }
  // 设置播放进度
  playPro() {
    let that = this;
    let { playProgess, duration } = this.state;
    console.log(duration)
    let n = 0;
    let timer;
    timer = setInterval(function () {
      n++;
      if (n > duration) {
        n = duration;
        clearInterval(timer);
      }
      that.setState({
        playProgess: n * (100 / duration)
      })
      // console.log(that.state.playProgess)
    }, 1000)

  }
  // 将秒转化成时分秒
  secTotime(s) {
    var t
    if (s > -1) {
      var hour = Math.floor(s / 3600)
      var min = Math.floor(s / 60) % 60
      var sec = s % 60
      if (hour < 10) {
        t = '0' + hour + ":"
      } else {
        t = hour + ":"
      }
      if (min < 10) {
        t += "0"
      }
      t += min + ":"
      if (sec < 10) {
        t += "0"
      }
      t += sec.toFixed(3)
    }
    return t
  }
  down=(src)=>{
    const downloadFileA = document.createElement('a')
document.body.append(downloadFileA)
downloadFileA.href= src;
downloadFileA.download = '下载文件.csv'
// 超链接 target="_blank" 要增加 rel="noopener noreferrer" 来堵住钓鱼安全漏洞。如果你在链接上使用 target="_blank"属性，并且不加上rel="noopener"属性，那么你就让用户暴露在一个非常简单的钓鱼攻击之下。(摘要)
downloadFileA.rel = 'noopener noreferrer'
downloadFileA.click()
document.body.removeChild(downloadFileA)
  }
}

export default MusicPlay;
